package com.ttsx.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ttsx.core.common.enums.OrderStatusEnum;
import com.ttsx.core.common.enums.PayStatusEnum;
import com.ttsx.pojo.entity.Order;
import com.ttsx.pojo.entity.Payment;
import com.ttsx.service.OrderService;
import com.ttsx.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 超时订单处理
 *
 * @author wb
 * @since 2025-11-07
 */

@Component
@Slf4j
public class UnpaidOrderCleanupTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentService paymentService;


    /**
     * 每10分钟执行一次
     */
    @Scheduled(fixedRate = 1000 * 60 * 10)
    public void clean() {
        LocalDateTime expireTime = LocalDateTime.now().minusMinutes(15);

        LambdaQueryWrapper<Order> orderLqw = new LambdaQueryWrapper<>();
        orderLqw.eq(Order::getOrderStatus, OrderStatusEnum.UNPAID.getCode())
                .lt(Order::getCreateTime, expireTime);

        List<Order> list = orderService.list(orderLqw);
        log.info("取消超时订单：{} 个", list.size());

        List<String> orderNos = new ArrayList<>();

        if (!list.isEmpty()) {
            // 更新订单状态
            for (Order order : list) {
                order.setOrderStatus(OrderStatusEnum.CANCELED.getCode());
                orderNos.add(order.getOrderNo());
            }
            orderService.updateBatchById(list);


            // 更新支付订单状态
            LambdaQueryWrapper<Payment> paymentLqw = new LambdaQueryWrapper<>();
            paymentLqw.in(Payment::getOrderNo, orderNos);
            List<Payment> paymentList = paymentService.list(paymentLqw);

            if (!paymentList.isEmpty()) {
                for (Payment payment : paymentList) {
                    payment.setPayStatus(PayStatusEnum.FAILED.getCode());
                }

                paymentService.updateBatchById(paymentList);
            }
        }
    }


}
